<!--
* description: 旧件管理-门店返件登记-编辑/修改
* author: wangjuan
* createdDate: 2021-3-4
-->
<template>
  <section class="editStoreReturnRegistration">
    <el-dialog
      v-dialogDrag
      :visible.sync="curPopupsVisible"
      :title="textMap[popupsState]"
      :append-to-body="true"
      width="70%"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="filter-container filter-title">返件信息</div>
      <div class="btns-container">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
          >{{ comp.text }}</el-button
        >
      </div>

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :format="comp.dateFormat"
            :date-type="comp.dateType"
            :data-to-object="comp.dataToObj"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div class="filter-container filter-title">旧件信息</div>
      <div class="app-container app-container-table">
        <one-table-template
          ref="returnTimeData"
          :key="oneTableKey"
          v-loading="loading"
          :dynamic-buttons="dynamicTableButtons"
          :dynamic-api-config="apiConfig"
          :dynamic-table-cols="tableCols"
          :dynamic-form-fields="formField"
          :dynamic-is-show-more-btn="true"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="true"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
        />

        <inEdit
          :key="inEditPopupsKey"
          :data-for-form="dataForForm"
          :popups-visible="inEditPopupsVisible"
          :popups-state="inEditPopupsState"
          @closeInEdit="closeInEdit"
          @returnTimeData="returnTimeData"
        />
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import { formMixins } from "@/components/mixins/formMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import api from "@/api/se/coreManagement";

export default {
  components: {
    OneTableTemplate,
    dialogHeader: () => import("@/components/dialogHeader"),
    inEdit: () => import("./inEdit"),
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins, formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },

  data() {
    const viewPageCode = "storeReturnRegistration-edit";

    return {
      apiConfig: api.CoreInfor,

      inEditPopupsKey: "inEditPopupsKey",
      inEditPopupsState: "",
      inEditPopupsVisible: false,

      dataForForm: {},
      selectData: {},
      loading: false,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          icon: "iconfont  icon-preservation",
          clickEvent: () => this.save(),
          text: this.$t("sys.button.save") /* 保存*/,
          position: "right",
        },
      ],
      dynamicTableButtons: [
        {
          compKey: "btnKey2",
          size: "small",
          name: "add",
          clickEvent: this.inEdit,
          text: "新增",
        },
        {
          compKey: "btnKey3",
          size: "small",
          name: "cancel",
          clickEvent: () => this.deleteDatas(),
          text: "删除",
          disabled: true,
        },
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
              {
                compKey: "compKey1",
                labelName: "返件单号：",
                codeField: "returnCode",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
                disabled: true,
              },
              {
                compKey: "compKey2",
                labelName: "返件类型：",
                codeField: "returnType",
                textField: "returnTypeName",
                component: () => import("@/components/org/commonSelect"),
                oFields: "returnType,returnTypeName",
                options: [
                  { returnType: "0", returnTypeName: "普通" },
                  { returnType: "1", returnTypeName: "快速" },
                ],
                type: "dropdownList",
                isRequire: true,
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey3",
                labelName: "返件方式：",
                codeField: "returnMethod",
                component: () => import("@/components/org/commonSelect"),
                oFields: "returnMethod,returnMethodName",
                options: [
                  { returnMethod: "0", returnMethodName: "快递" },
                  { returnMethod: "1", returnMethodName: "自送" },
                  { returnMethod: "2", returnMethodName: "现场自取" },
                ],
                type: "dropdownList",
                isRequire: true,
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey4",
                labelName: "运费：",
                codeField: "expressFee",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                // isRequire: true,
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey5",
                labelName: "物流公司：",
                codeField: "expressName",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey6",
                labelName: "物流单号：",
                codeField: "expressCode",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey7",
                labelName: "返件日期：",
                codeField: "realDate",
                component: () =>
                  import("@/components/org/datePicker/datePicker"),
                dateType: "datetime",
                dateFormat: "yyyy-MM-dd HH:mm:ss",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey8",
                labelName: "返件状态：",
                codeField: "returnStatus",
                textField: "returnStatusName",
                component: () => import("@/components/org/commonSelect"),
                oFields: "returnStatus,returnStatusName",
                options: [
                  { returnStatus: "0", returnStatusName: "已登记" },
                  { returnStatus: "1", returnStatusName: "已发运" },
                  { returnStatus: "2", returnStatusName: "已收货" },
                ],
                type: "dropdownList",
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey9",
                labelName: "备注：",
                codeField: "remark",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
              },
            ],
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "releaseId",
                label: "主键ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "preAuthorCode",
                label: "索赔单号",
                align: "center",
              },
              {
                prop: "partCode",
                label: "备件编码",
                align: "center",
              },
              {
                prop: "partName",
                label: "备件名称",
                align: "center",
              },
              {
                prop: "coreBarcode",
                label: "旧件条码号",
                align: "center",
              },
            ],
      // 标题
      textMap: {
        edit: "编辑返件登记",
        add: "新增返件登记",
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          returnCode: "",
          returnType: "",
          returnTypeName: "",
          returnMethod: "",
          returnMethodName: "",
          expressFee: "",
          expressName: "",
          expressCode: "",
          realDate: "",
          returnStatus: "",
          returnStatusName: "",
          remark: "",
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection;

          this.handleSelectionChange(selection);
        },
      },
    };
  },

  watch: {
    curPopupsVisible: {
      handler: function (val) {
        if (val) {
          if (this.popupsState == "add") {
            this.$requestAPI({
              apiUrl: api.returnNo.APIUrl,
              variables: {},
            }).then((response) => {
              if (response.result === "1") {
                this.formField.returnCode = response.rows[0].returnCode;
              }
            });
          } else {
            this.queryTable(1);
          }
        }
      },
    },
  },

  methods: {
    inEdit() {
      this.inEditPopupsVisible = true;
      this.dataForForm = this.formField;
    },
    returnTimeData(val) {
      this.$refs.returnTimeData.list = val;
      // console.log("val------------", val);
      console.log(this.$refs);
    },
    // 新增/编辑保存按钮
    save() {
      const that = this;
      this.$utils.validataMoth(this, "validpopup");
      if (this.valid) {
        if (that.popupsState === "edit") {
          that.editSave();
        } else {
          that.addSave();
        }
      }
    },

    // 编辑保存
    editSave() {
      const that = this;
      const queryObj = {
        type: "mutation",
        apiConfig: api.rtuRegistrationUpd,
        variables: {
          returnCode: that.formField.returnCode,
          returnType: that.formField.returnType,
          returnMethod: that.formField.returnMethod,
          expressName: that.formField.expressName,
          expressFee: that.formField.expressFee,
          expressCode: that.formField.expressCode,
          realDate: that.formField.realDate,
          returnStatus: that.formField.returnStatus,
          remark: that.formField.remark,
          list: this.$refs.returnTimeData.list,
        },
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.$message({
            message: response.msg,
            type: "success",
            duration: 1000,
          });
          this.$emit("update:popupsVisible", false);
          this.$parent.queryTable(1);
        } else {
          this.$message({
            message: response.msg,
            type: "warn",
            duration: 1000,
          });
        }
      });
    },

    // 新增保存
    addSave() {
      const that = this;
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: api.rtuRegistrationAdd,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          returnCode: that.formField.returnCode,
          returnType: that.formField.returnType,
          returnMethod: that.formField.returnMethod,
          expressName: that.formField.expressName,
          expressFee: that.formField.expressFee,
          expressCode: that.formField.expressCode,
          realDate: that.formField.realDate,
          returnStatus: that.formField.returnStatus,
          remark: that.formField.remark,
          listData: this.$refs.returnTimeData.list,
        },
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.$message({
            message: response.msg,
            type: "success",
            duration: 1000,
          });
          this.$emit("update:popupsVisible", false);
          this.$parent.queryTable(1);
        } else {
          this.$message({
            message: response.msg,
            type: "warn",
            duration: 1000,
          });
        }
      });
    },

    deleteDatas() {
      const that = this;
      const queryObj = {
        type: "mutation",
        apiConfig: api.coreInfoDel,
        variables: {
          list: that.selectData.reduce((pre, cur, idx) => {
            const { partId } = cur;
            pre.push({ partId });
            return pre;
          }, []),
        },
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === "1") {
          this.$message({
            message: response.msg,
            type: "success",
            duration: 1000,
          });
          this.queryTable(1);
        } else {
          this.$message({
            message: response.msg,
            type: "warn",
            duration: 1000,
          });
        }
      });
    },

    closeEdit() {
      this.$emit("update:popupsVisible", false);
      this.oneTableKey = this.$utils.generateId();
    },

    // 关闭保存弹窗
    closeInEdit() {
      this.inEditPopupsVisible = false;
      this.queryTable(1);
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicTableButtons.filter(
        (o) => o.disabled !== undefined
      );
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0;
        btns.forEach((item) => {
          item.disabled = !isCheck;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.btns-container {
  width: 100%;
  height: 30px;
  padding: 0 20px;
  background-color: #fff;
  .el-button {
    float: right;
    margin-left: 10px;
  }
}
.filter-title {
  font-size: 18px;
  font-weight: bolder;
}
.filter-container.filter-title::before {
  border-left: 4px solid #0075ff;
  padding-right: 10px;
  height: 20px;
  left: 0px;
  top: 4px;
}
</style>

